package com.gz.mylife.app;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.NetworkUtil;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.EquimentConfirmListener;
import com.zl.smartmall.library.po.Component;
import com.zl.smartmall.library.po.EquipmentImage;
import com.zl.smartmall.library.po.ForecastPrice;
import com.zl.smartmall.library.po.MaintenacesInfo;
import com.zl.smartmall.library.util.Constants;

public class MyEquimentDetail extends BaseActivity implements OnClickListener,
OnLoadingCoverRefreshListener {

	private static final String TAG = MyEquimentDetail.class.getSimpleName();
	private LoadingCover mLoadingCover;
	private TextView tv_order_status;// 顶部的订单状态
	private TextView tv_order_code;// 维修单号
	private TextView repair_item;// 维修项目
	private TextView create_time;// 报修时间
	private TextView personname;// 联系人姓名
	private TextView repair_address;// 维修地址
	private TextView repair_content;// 维系详情
	private TextView repair_name;// 维修方
	private TextView create_start;// 开始时间
	private TextView create_end;// 结束时间
	private TextView repair_result;// 维修结果
	private TextView create_save;// 录入时间
	private LinearLayout pictures;//维修图片
	private ImageView[] picture;
	private DisplayImageOptions mPictureOption;
	private LinearLayout layout_product_item;
	private View line_3;
	private Dialog mConfirmDialog;
	private LayoutInflater mInflater;
	private EquimentConfirmListener listener;
	private OfflineDialog mOfflineDialog;
	private Button btn_confirm_the_goods;// 确认完成按钮
	MaintenacesInfo infos = new MaintenacesInfo();
	private String[] img = new String[4];
	private TextView tv_comment;//评价
	private TextView tx_ischarge;//是否有偿服务
	private TextView price;//参考价
	private TextView tx_realmoney;//实际维修费
	private TextView tx_forecastprice;//报价
	private TextView tx_lingjian;//零部件价格及数量
	private ListView listview;//零部件以及数量
	private MyAdapter1 myadapter;//零部件适配器
	private List<Component> components;//零部件的数据
	private String distribute_id;//派单单号
	private LinearLayout ly_top;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_equiment_detail);
		initListener();
		setActionbarTitle("申报详情", true);
		Bundle bundle = this.getIntent().getExtras();
		infos = (MaintenacesInfo) bundle.getSerializable("mainlist");
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mPictureOption = buildPictureOptions();
		pictures = (LinearLayout) findViewById(R.id.pictures);
		tv_order_status = (TextView) findViewById(R.id.tv_order_status);
		tv_order_code = (TextView) findViewById(R.id.tv_order_code);
		repair_item = (TextView) findViewById(R.id.repair_item);
		create_time = (TextView) findViewById(R.id.create_time);
		personname = (TextView) findViewById(R.id.personname);
		repair_address = (TextView) findViewById(R.id.repair_address);
		repair_content = (TextView) findViewById(R.id.repair_content);
		repair_name = (TextView) findViewById(R.id.repair_name);
		create_start = (TextView) findViewById(R.id.create_start);
		create_end = (TextView) findViewById(R.id.create_end);
		repair_result = (TextView) findViewById(R.id.repair_result);
		create_save = (TextView) findViewById(R.id.create_save);
		layout_product_item = (LinearLayout) findViewById(R.id.layout_product_item);
		tx_ischarge = (TextView) findViewById(R.id.tx_ischarge);
		price = (TextView) findViewById(R.id.price);
		line_3 = (View) findViewById(R.id.line_3);
		picture = new ImageView[] {
				(ImageView) findViewById(R.id.iv_picture1),
				(ImageView) findViewById(R.id.iv_picture2),
				(ImageView) findViewById(R.id.iv_picture3),
				(ImageView) findViewById(R.id.iv_picture4) };
		for(ImageView view : picture) {
			view.setOnClickListener(this);
		}
		mInflater = getLayoutInflater();
		View confirmView = mInflater.inflate(R.layout.confirm_the_goods_dialog,
				null);
		confirmView.findViewById(R.id.btn_confirm).setOnClickListener(this);
		confirmView.findViewById(R.id.btn_cancel).setOnClickListener(this);
		TextView title = (TextView) confirmView.findViewById(R.id.title);
		title.setText("请确认维修完成,否则维修方不承担责任");
		mConfirmDialog = new Dialog(this, R.style.DialogTheme);
		mConfirmDialog.setContentView(confirmView);
		mConfirmDialog.setCancelable(true);
		mOfflineDialog = (OfflineDialog) mInflater.inflate(R.layout.offline_dialog, null);
		btn_confirm_the_goods = (Button) findViewById(R.id.btn_confirm_the_goods);
		btn_confirm_the_goods.setOnClickListener(this);
		tv_comment = (TextView) findViewById(R.id.tv_comment);
		tv_comment.setOnClickListener(this);
		if ("完成".equals(infos.getStatus())) {
			tv_order_status.setBackgroundResource(R.drawable.bg_order_status_dark_circle);
			tv_order_status.setText("已完成");
			btn_confirm_the_goods.setVisibility(View.GONE);
			layout_product_item.setVisibility(View.VISIBLE);
			tv_comment.setVisibility(View.VISIBLE);
			line_3.setVisibility(View.VISIBLE);
		} else if ("待处理".equals(infos.getStatus())) {
			tv_order_status.setBackgroundResource(R.drawable.bg_order_status_green_circle);
			tv_order_status.setText("待处理");
			tv_comment.setVisibility(View.GONE);
		} else if("处理中".equals(infos.getStatus())) {
			tv_order_status.setBackgroundResource(R.drawable.bg_order_status_green_circle);
			tv_order_status.setText("处理中");
			layout_product_item.setVisibility(View.VISIBLE);
			line_3.setVisibility(View.VISIBLE);
			tv_comment.setVisibility(View.GONE);
		}
		else if("已反馈".equals(infos.getStatus())){
			tv_order_status.setBackgroundResource(R.drawable.bg_order_status_green_circle);
			tv_order_status.setText("已反馈");
			layout_product_item.setVisibility(View.VISIBLE);
			tv_comment.setVisibility(View.GONE);
			line_3.setVisibility(View.VISIBLE);
		}else if("已派单".equals(infos.getStatus())){
			tv_order_status.setBackgroundResource(R.drawable.bg_order_status_green_circle);
			tv_order_status.setText("已派单");
			layout_product_item.setVisibility(View.VISIBLE);
			line_3.setVisibility(View.VISIBLE);
			tv_comment.setVisibility(View.GONE);
		}
		tv_order_code.setText("申报单号:" + infos.getCode());
		repair_item.setText(infos.getRepairitem());
		create_time.setText(infos.getCreatedat());
		personname.setText(infos.getApplyname());
		repair_address.setText(infos.getAddress());
		repair_content.setText(infos.getInfo());// 详情
		price.setText("null".equals(infos.getReference_price())?"00.00":infos.getReference_price());
		tx_ischarge.setText(infos.getIs_charged().equals("1")?"是否有偿服务：有偿":"是否有偿服务：无偿");
		tx_forecastprice = (TextView) findViewById(R.id.tx_forecastprice);
		tx_realmoney = (TextView) findViewById(R.id.tx_realmoney);
		components = new ArrayList<Component>();
		listview = (ListView) findViewById(R.id.listview);
		myadapter = new MyAdapter1();
		listview.setAdapter(myadapter);
		ly_top = (LinearLayout) findViewById(R.id.ly_top);
		if (infos.getMaindetails().size() != 0) {
			repair_name.setText(infos.getMaindetails().get(0).getMaintainer());
			String start = infos.getMaindetails().get(0).getBeginat();
			String end = infos.getMaindetails().get(0).getEndat();
			if (!" ".equals(start) && !("null".equals(start))) {
				create_start.setText(start.substring(0,10)+" "+start.substring(11,19));
			}
			if (!" ".equals(end) && !("null".equals(end))) {
				create_end.setText(end.substring(0,10)+" "+end.substring(11,19));
			}
			if (!"".equals(infos.getMaindetails().get(0).getDetailresult()) && !("null".equals(infos.getMaindetails().get(0).getDetailresult()))) {
				repair_result.setText(infos.getMaindetails().get(0).getDetailresult());
			}
			create_save.setText(infos.getMaindetails().get(0).getDetailcreated_at());
			if (!"".equals(infos.getMaindetails().get(0).getReference_price()) && !("null".equals(infos.getMaindetails().get(0).getReference_price()))) {
				tx_forecastprice.setText(infos.getMaindetails().get(0).getReference_price()+"");
			}
			if (!"".equals(infos.getMaindetails().get(0).getReal_money()) && !("null".equals(infos.getMaindetails().get(0).getReal_money()))) {
				tx_realmoney.setText(infos.getMaindetails().get(0).getReal_money());
			}
			distribute_id = infos.getMaindetails().get(0).getDistribute_id();
		}
		tx_lingjian = (TextView) findViewById(R.id.tx_lingjian);
		tx_lingjian.setOnClickListener(this);
		/**
		 * 显示维修上报的图片
		 */
		if (infos.getImage().size()!=0) {

			if (infos.getImage().get(0).getImage_1()!=null&&!infos.getImage().get(0).getImage_1().equals("null")) {
				pictures.setVisibility(View.VISIBLE);
				EquipmentImage image = new EquipmentImage();
				image = infos.getImage().get(0);
				img[0] = image.getImage_1();
				img[1] = image.getImage_2();
				img[2] = image.getImage_3();
				img[3] = image.getImage_4();
				for (int i = 0; i < 4; i++) {
					if (i < img.length) {
						if (!img[i].equals("null")&&img[i]!=null) {
							picture[i].setVisibility(View.VISIBLE);
							ImageLoader.getInstance().displayImage(
									Constants.URL_HOST_RUBY+"/repair_apply_images/"+img[i], picture[i],
									mPictureOption);
						}else {
							picture[i].setVisibility(View.GONE);
						}
					} 
				}
			}else {
				pictures.setVisibility(View.GONE);
			}

		} 
		
		
	}

	private DisplayImageOptions buildPictureOptions() {
		return new DisplayImageOptions.Builder().resetViewBeforeLoading(true)
				.bitmapConfig(Bitmap.Config.ARGB_8888).cacheInMemory(true)
				.cacheOnDisk(true).showImageOnLoading(R.color.transparent)
				.showImageOnFail(R.color.transparent)
				.showImageForEmptyUri(R.color.transparent)
				.imageScaleType(ImageScaleType.EXACTLY).build();
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_confirm_the_goods:// 点击确认完成按钮，更新维修申报的状态
			mConfirmDialog.show();
			break;
		case R.id.btn_confirm:
			ISmartMall.getInstance().updateRepair(infos.getCode(), listener);

		case R.id.btn_cancel:
			mConfirmDialog.dismiss();
			break;
		case R.id.iv_picture1:
			thumbnailClickEvent(0);
			break;

		case R.id.iv_picture2:
			thumbnailClickEvent(1);
			break;

		case R.id.iv_picture3:
			thumbnailClickEvent(2);
			break;

		case R.id.iv_picture4:
			thumbnailClickEvent(3);
			break;
		case R.id.tv_comment:
			Intent intent = new Intent(getApplicationContext(), EquimentCommentIssue.class);
			intent.putExtra("repair_apply_id", infos.getRepair_apply_id());
			intent.putExtra("comments", (Serializable)infos.getComments());
			intent.putExtra("address", getIntent().getStringExtra("address"));
			intent.putExtra("mallcomid", getIntent().getStringExtra("mallcomid"));
			startActivity(intent);
			break;
		case R.id.tx_lingjian://点击查看零部件价格及数量
			info_repair_list(distribute_id);
			break;
		}
		

	}

	private void initListener() {

		listener = new EquimentConfirmListener() {

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(),Define.MSG_OPERATE_FAILED_RETRY);
			}

			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(),Define.MSG_NO_NETWORK);
			}

			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				setResult(Define.ACTIVITY_CODE_ORDER_SIGN);
				ISmartMall.getInstance().updateRepair(infos.getCode(), listener);
				tv_order_status.setBackgroundResource(R.drawable.bg_order_status_dark_circle);
				tv_order_status.setText("已完成");
				btn_confirm_the_goods.setVisibility(View.GONE);
			}

			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub

			}

		};

	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub

	}
	private void thumbnailClickEvent(int item) {
		ArrayList<String> url = new ArrayList<String>();
		for (int i = 0; i < img.length; i++) {
			if (img[i]!=null&&!img[i].equals("null")) {
				url.add(Constants.URL_HOST_RUBY+"/repair_apply_images/"+img[i]);
			}
		}
		Intent intent = new Intent(getApplicationContext(), HDPictureBrowse.class);
		intent.putStringArrayListExtra("picture", url);
		intent.putExtra("position", item);
		startActivity(intent);

	}  
	
	private class MyAdapter1 extends BaseAdapter {

		@Override
		public int getCount() {
			return components.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return components.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder1 holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.forecast_item, null);
				holder = new ViewHolder1();
				holder.forecast_name = (TextView) convertView.findViewById(R.id.forecast_name);
				holder.forecast_price = (TextView) convertView.findViewById(R.id.forecast_price);
				holder.forecast_unit = (TextView) convertView.findViewById(R.id.forecast_unit);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder1) convertView.getTag();
			}
			holder.forecast_name.setText(components.get(position).getName());
			holder.forecast_price.setText(components.get(position).getPrice());
			holder.forecast_unit.setText(components.get(position).getUse_num());
			return convertView;
		}
	}
	private class ViewHolder1 {
		TextView forecast_name;
		TextView forecast_price;
		TextView forecast_unit;
		
	}
	/**
	 * 报价信息
	 */
	private void info_repair_list(String distribute_id) {

		if (NetworkUtil.isNetworkConnected(MyEquimentDetail.this)) {
			String url = Constants.URL_HOST_RUBY+"/android_oa/info_repair_distribute_price_list";
			RequestParams params = new RequestParams(url);
			params.addParameter("distribute_id", distribute_id);
			Log.i("duzhijuan", params + "?distribute_id="+distribute_id);
			x.http().get(params, new Callback.CommonCallback<String>() {

				@Override
				public void onCancelled(CancelledException arg0) {
					// TODO Auto-generated method stub
					Log.e("cancelled", arg0.toString());
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// TODO Auto-generated method stub
					Log.e("onError", arg0.toString());
				}

				@Override
				public void onFinished() {
					// TODO Auto-generated method stub
					Log.e("onFinished","onFinished");
				}

				@Override
				public void onSuccess(String result) {
					// TODO Auto-generated method stub
					try {
						JSONObject jsonObject = new JSONObject(result.toString());
						if ("0".equals(jsonObject.getString("ret"))) {
							components.clear();
							components.addAll(Component.parse(jsonObject.getJSONArray("result")));
							if (components.size()>0) {
								listview.setVisibility(View.VISIBLE);
								ly_top.setVisibility(View.VISIBLE);
								fixListViewHeight(listview);
								myadapter.notifyDataSetChanged();
							}else{
								Toast.makeText(MyEquimentDetail.this, jsonObject.getString("~未使用零件~"), Toast.LENGTH_LONG).show();
							}
						}else{
							Toast.makeText(MyEquimentDetail.this, jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}

			});
		}else{
			Toast.makeText(MyEquimentDetail.this, "糟糕,网络异常!", Toast.LENGTH_LONG).show();
		}

	}
	 public void fixListViewHeight(ListView listView) {   
	        // 如果没有设置数据适配器，则ListView没有子项，返回。  
	        ListAdapter listAdapter = listView.getAdapter();  
	        int totalHeight = 0;   
	        if (listAdapter == null) {   
	            return;   
	        }   
	        for (int index = 0, len = listAdapter.getCount(); index < len; index++) {     
	            View listViewItem = listAdapter.getView(index , null, listView);  
	            // 计算子项View 的宽高   
	            listViewItem.measure(0, 0);    
	            // 计算所有子项的高度和
	            totalHeight += listViewItem.getMeasuredHeight();    
	        }   
	        ViewGroup.LayoutParams params = listView.getLayoutParams();   
	        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));   
	        listView.setLayoutParams(params);   

	    }   

}
